package com.xuecheng.auth.config;

import com.alibaba.fastjson.JSONObject;
import com.xuecheng.auth.service.UserJwt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.provider.token.DefaultUserAuthenticationConverter;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class CustomUserAuthenticationConverter extends DefaultUserAuthenticationConverter {
    @Autowired
    UserDetailsService userDetailsService;

    @Override
    public Map<String, ?> convertUserAuthentication(Authentication authentication) {
        Map<String, Object> response = new HashMap<>();
        System.out.println(authentication);
        String username = authentication.getName();
//        System.out.println(username);
        JSONObject jsonObject= (JSONObject)  com.alibaba.fastjson.JSON.parse(username);
        String s = (String) jsonObject.get("username");


        response.put("user_name", username);
        Object principal = authentication.getPrincipal();
//        System.out.println(principal);


        UserJwt userJwt = null;
        UserDetails userDetails = null;
        if(principal instanceof  UserJwt){
            userJwt = (UserJwt) principal;
        }else{

            //refresh_token默认不去调用userdetailService获取用户信息，这里我们手动去调用，得到 UserJwt
            userDetails = userDetailsService.loadUserByUsername(s);
//            String UD_username = userDetails.getUsername();

//            userJwt = (UserJwt) userDetails;//TODO
        }
        response.put("name", userJwt.getName());
        response.put("id", userJwt.getId());
        response.put("utype",userJwt.getUtype());
        response.put("userpic",userJwt.getUserpic());
        response.put("companyId",userJwt.getCompanyId());
//        response.put("password", userDetails.getPassword());

        if (authentication.getAuthorities() != null && !authentication.getAuthorities().isEmpty()) {
            response.put("authorities", AuthorityUtils.authorityListToSet(authentication.getAuthorities()));
        }

        return response;
    }


}
